using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

using Impact.Infrastructure;
using System.Collections.Generic;

namespace Impact.Web.Admin.Controls
{
    /// <summary>
    /// code-behind for the file picker control
    /// </summary>
    public partial class FilePicker : UserControl
    {

        /// <summary>
        /// performs extra processing when starting up
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!IsPostBack)
            {
                string path = Server.MapPath(BasePath);
                AddFolder(new DirectoryInfo(path), path);
                filePicker.SelectedValue = initSelectedValue;
            }
        }


        private void AddFolder(DirectoryInfo folder, string rootPath)
        {

            List<FileInfo> files = new List<FileInfo>();
            files.AddRange(folder.GetFiles("*.jpg", SearchOption.AllDirectories));
            files.AddRange(folder.GetFiles("*.png", SearchOption.AllDirectories));
            files.AddRange(folder.GetFiles("*.gif", SearchOption.AllDirectories));
            
            foreach (FileInfo file in files)
            {
                string shortPath = file.FullName.Replace(rootPath, string.Empty);
                filePicker.Items.Add(shortPath);
            }

        }

        /// <summary>
        /// event handler to validate that the control is valid
        /// </summary>
        protected void ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = filePicker.SelectedIndex > 0;
        }

        /// <summary>
        /// gets or sets the root folder to start the folder treeview from
        /// </summary>
        public string BasePath
        {
            get { return initBasePath; }
            set { initBasePath = value; }
        }
        private string initBasePath;

        /// <summary>
        /// gets or sets the path for the selected file
        /// </summary>
        public string SelectedFilePath
        {
            get { return filePicker.SelectedValue; }
            set { initSelectedValue = value; }
        }
        private string initSelectedValue;

    }
}